package com.ocean.client.extension.security.filter;

import com.ocean.cache.redis.IRedisCache;
import com.ocean.client.extension.ConstantsCacheExtension;
import com.ocean.client.extension.security.core.UmsMemberDetails;
import com.ocean.core.util.JwtUtil;
import com.ocean.security.filter.CustomOncePerRequestFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Token过滤器
 *
 * @author zhang
 * @since 2023/11/24
 */
@Component
public class CustomPerRequestFilter extends CustomOncePerRequestFilter {

    @Autowired
    private IRedisCache iRedisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authentication = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (JwtUtil.checkToken(authentication)) {
            String userId = JwtUtil.parseJwt(authentication).getId();
            UmsMemberDetails userDetails = (UmsMemberDetails) iRedisCache.get(ConstantsCacheExtension.getInstance().getAuthenticationPrefix() + userId);
            super.authentication(userDetails);
        }
        filterChain.doFilter(request, response);
    }
}
